package com.wei;

/**
 * 两个线程依次打印,结果如下12A34B56C...
 *
 * @author :sunwei
 * @description:
 * @date create in 23:05  2021/7/27
 */
public class PrintProblem {
    
    private static final Object LOCK = new Object();
    
    //1:数字,2:字母
    private static int flag = 1;
    
    private static volatile int count = 1;
    
    private static void printNumber() {
        synchronized (LOCK) {
            while (flag == 2) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            flag = 2;
            System.out.print( (2 * count - 1) + "" +  2 * count);
            
            LOCK.notifyAll();
        }
    }
    
    private static void printWord() {
        synchronized (LOCK) {
            while (flag == 1) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            flag = 1;
            System.out.print(Character.toString((char) (count - 1) + 'A'));
            count++;
            
            LOCK.notifyAll();
        }
    }
    
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 26; i++) {
                printNumber();
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 26; i++) {
                printWord();
            }
        });
        
        t1.start();
        t2.start();
    }
}
